package com.sczmgk.hotline;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.sczmgk.hotline.base.CheckPermissionBaseActivity;
import com.sczmgk.hotline.callback.MainHomeHandlerCallback;
import com.sczmgk.hotline.mainhomeview.MainHomeFind;
import com.sczmgk.hotline.mainhomeview.MainHomeHome;
import com.sczmgk.hotline.mainhomeview.MainHomePersonal;
import com.sczmgk.hotline.mainhomeview.MainHomeRule;
import com.sczmgk.hotline.service.MsgTimerService;
import com.sczmgk.hotline.utils.CheckboxUtils;
import com.sczmgk.hotline.utils.MyLog;
import com.sczmgk.hotline.utils.MyToast;
import com.sczmgk.hotline.view.MyRadioButton;
import com.sczmgk.hotline.view.MyViewPager;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends CheckPermissionBaseActivity {

    private final String TAG = MainActivity.class.getSimpleName();

    //
    public static final int CHAT_REQUEST_CODE = 128;

    //回调
    private MainHomeHandlerCallback mainHomeHandlerCallback;

    //handler
    protected Handler mHandler = null;

    //主页viewpager
    private MyViewPager mViewPager;
    private MyViewPageAdapter myPagerAdapter;

    //底部按钮容器
    public static RadioGroup mRadioGroup;

    //页面list
    private List<View> lists;

    //上一次点击的position
    private int lastPosition = 0;

    //定时服务
//    public static MsgTimerService msgTimerService;

    /**
     * 菜单的文字
     */
    private String[] menuTitles;
    /**
     * 菜单图片的id
     */
    private int[] menuIcons;

    private boolean isFirstBack = true;

    private MainHomeHome mainHomeHome;

    private MainHomeFind mainHomeFind;

    private MainHomePersonal mainHomePersonal;

    private MainHomeRule mainHomeRule;

    private void initHandler() {
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                if (mainHomeHandlerCallback != null) {
                    MyLog.d(TAG, "MainActivity   发消息了！");
                    mainHomeHandlerCallback.onHandleMessage(msg);
                }
            }
        };
    }

    @Override
    public void handleMessage(Message msg) {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setHeadViewVisibility(View.GONE);
        initHandler();

        Button online = (Button) findViewById(R.id.bt_online);
        online.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loginTest(false);
            }
        });
        initView();
        setListeners();
//        initService();
    }

    private void initView() {
        mViewPager = (MyViewPager) findViewById(R.id.vp_main_home);
        //初始化底部导航
        initRadioButton();
        //初始化四个主页的View
        initViewPagerItem();
        myPagerAdapter = new MyViewPageAdapter();
        mViewPager.setAdapter(myPagerAdapter);
        mViewPager.setOffscreenPageLimit(4);
        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if (position >= 2) {
                    position += 1;
                }
                RadioButton rb = (RadioButton) mRadioGroup.getChildAt(position);
                rb.setChecked(true);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    private void initService() {
        Intent intent = new Intent(MainActivity.this, MsgTimerService.class);
        MainActivity.this.bindService(intent, myConn, Context.BIND_AUTO_CREATE);
    }

    private ServiceConnection myConn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
//            msgTimerService = ((MsgTimerService.Mybinder) service).getService();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };

    /**
     * 取得Maihome的Hander
     */
    public Handler getmHandler() {
        return mHandler;
    }

    public void setMainHomeHandlerCallback(MainHomeHandlerCallback mainHomeHandlerCallback) {
        MyLog.d(TAG, "设置handlecallback: " + mainHomeHandlerCallback.getClass());
        this.mainHomeHandlerCallback = mainHomeHandlerCallback;
    }

    private void setListeners() {

        mRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.rb_main_home:
                        lastPosition = 0;
                        mViewPager.setCurrentItem(0);
                        setMainHomeOnResume();
                        break;
                    case R.id.rb_rule:
                        lastPosition = 1;
                        mViewPager.setCurrentItem(1);
                        setRuleOnResume();
                        break;
                    case R.id.rb_chat:
                        MyRadioButton radioButton = (MyRadioButton) mRadioGroup.getChildAt(lastPosition);
                        radioButton.setChecked(true);

                        loginTest(true);

                        break;
                    case R.id.rb_find:
                        lastPosition = 3;
                        mViewPager.setCurrentItem(2);
                        setFindOnResume();
                        break;
                    case R.id.rb_personal:
                        lastPosition = 4;
                        mViewPager.setCurrentItem(3);
                        setMeOnResume();
                        break;
                }
            }
        });

        mViewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                if (position >= 2) {
                    position += 1;
                }
                RadioButton rb = (RadioButton) mRadioGroup.getChildAt(position);
                rb.setChecked(true);
            }
        });
    }

    /**
     * 初始化RadioButton
     */
    private void initRadioButton() {
        //图片及文字的资源
        menuTitles = getResources().getStringArray(R.array.main_home_menu);
        menuIcons = new int[]{R.drawable.load_default_center, R.drawable.load_default_center, R.drawable.chat_android, R.drawable.load_default_center, R.drawable.load_default_center};
        mRadioGroup = (RadioGroup) findViewById(R.id.rg_nav);//找到RadioGroup

        for (int i = 0; i < mRadioGroup.getChildCount(); i++) {//迭代设置各个RadioButton图片及资源
            MyRadioButton rb = (MyRadioButton) mRadioGroup.getChildAt(i);//找到RadioButton
            if (i == 2) {
                CheckboxUtils.setRadioButtonImageBg(rb, MainActivity.this, menuIcons[i]);
            } else {
                CheckboxUtils.setRadioButtonImage(rb, MainActivity.this, menuIcons[i]);
                rb.setDrawable(menuIcons[i], false);
                rb.setText(menuTitles[i]);//设置文字
            }

            rb.setGravity(Gravity.CENTER);
            if (i == 0) {//将第一个设置成选中状态
                rb.setChecked(true);
                mViewPager.setCurrentItem(0);
            }
        }
    }

    private void initViewPagerItem() {
        lists = new ArrayList<>();
        // 首页
        mainHomeHome = new MainHomeHome(this);
        View mainHomeView = mainHomeHome.getView();
        lists.add(mainHomeView);

        // 政策法规
        mainHomeRule = new MainHomeRule(this);
        View mainHomeApplicationView = mainHomeRule.getView();
        lists.add(mainHomeApplicationView);

        // 发现
        mainHomeFind = new MainHomeFind(this);
        View mainHomeChatView = mainHomeFind.getView();
        lists.add(mainHomeChatView);

        // 个人
        mainHomePersonal = new MainHomePersonal(this);
        View mainHomePersonalView = mainHomePersonal.getView();
        lists.add(mainHomePersonalView);
    }

    /**
     * 设置主页得到焦点其它失去焦点
     */
    private void setMainHomeOnResume() {
        mainHomeHome.onResume();
        mainHomeRule.onPause();
        mainHomeFind.onPause();
        mainHomePersonal.onPause();
    }

    /**
     * 设置政策法规得到焦点
     */
    private void setRuleOnResume() {
        mainHomeRule.onResume();
        mainHomeHome.onPause();
        mainHomeFind.onPause();
        mainHomePersonal.onPause();
    }

    /**
     * 设置发现得到焦点
     */
    private void setFindOnResume() {
        mainHomeFind.onResume();
        mainHomeRule.onPause();
        mainHomeHome.onPause();
        mainHomePersonal.onPause();
    }

    /**
     * 设置我的得到焦点
     */
    private void setMeOnResume() {
        mainHomePersonal.onResume();
        mainHomeRule.onPause();
        mainHomeHome.onPause();
        mainHomeFind.onPause();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mainHomeHome.onPause();
        mainHomeFind.onPause();
        mainHomeRule.onPause();
        mainHomePersonal.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        int checkedId = mRadioGroup.getCheckedRadioButtonId();
        switch (checkedId) {
            case R.id.rb_main_home:
                setMainHomeOnResume();
                break;
            case R.id.rb_rule:
                setRuleOnResume();
                break;
            case R.id.rb_find:
                setFindOnResume();
                break;
            case R.id.rb_personal:
                setMeOnResume();
                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (videoView.getVisibility() == View.VISIBLE) {
                // TODO hideCustomVideoView
                return true;
            } else {
                //处理返回键
                new Timer().schedule(new TimerTask() {
                    @Override
                    public void run() {
                        isFirstBack = true;
                    }
                }, 2000);
                if (isFirstBack) {
                    MyLog.d(TAG, " 第一次按 Back   isFirstBack:" + isFirstBack);
                    MyToast.show(MainActivity.this, getString(R.string.main_goback_hint));
                    isFirstBack = false;
                    return true;
                } else {
                    MyLog.d(TAG, " -----------第二次按 Back   isFirstBack:" + isFirstBack);
                    return super.onKeyDown(keyCode, event);
                }
            }

        } else {
            return super.onKeyDown(keyCode, event);
        }
    }

    @Override
    public Resources getResources() {
        Resources res = super.getResources();
        Configuration config = new Configuration();
        config.setToDefaults();
        res.updateConfiguration(config, res.getDisplayMetrics());
        return res;
    }

    private class MyViewPageAdapter extends PagerAdapter {

        public MyViewPageAdapter() {
            super();
        }

        @Override
        public int getCount() {
            return lists.size();
        }


        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }


        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            View item = lists.get(position);
            container.addView(item);
            return item;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            View item = lists.get(position);
            container.removeView(item);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case CHAT_REQUEST_CODE:
                    // TODO 调用服务的开启定时器方法
                    if (data != null) {
                        boolean isAndroid = data.getBooleanExtra("isAndroid", true);
//                        msgTimerService.startTimer(isAndroid);
                    }
                    break;
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        try {
//            unbindService(myConn);
//            Intent intent = new Intent(MainActivity.this, MsgTimerService.class);
//            stopService(intent);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
    }

    @Override
    public void onSelectedPhonePermission(String phoneNumber) {

    }

    @Override
    public void onSelectedStroage(int position) {

    }

    @Override
    public void onSelectCamera(int position) {

    }

    @Override
    public boolean getIsNeedLogin() {
        return false;
    }
}
